﻿using Microsoft.EntityFrameworkCore;
using MyECommerceProject.Interfaces;
using MyECommerceProject.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace MyECommerceProject.Data
{
    public class InventoryRepository : IInventoryRepository
    {
        private readonly MyDbContext _context;

        public InventoryRepository(MyDbContext context)
        {
            _context = context;
        }
        public async Task AddInventoryRecordAsync(Inventory inventory)
        {
            _context.Inventories.Add(inventory);
            await _context.SaveChangesAsync();
        }

        public async Task<IEnumerable<Inventory>> GetInventoryRecordsAsync(int productId, DateOnly startDate, DateOnly endDate)
        {
            return await _context.Inventories
                .Where(i => i.ProductId == productId && i.OperationDate >= startDate && i.OperationDate <= endDate)
                .ToListAsync();
        }
        
        //后面代码一定会精简一下的

        public async Task<IEnumerable<Inventory>> GetInventoriesAsync()
        {
            return await _context.Inventories.Include(i => i.Product).ToListAsync();
        }

        public async Task<Inventory> GetInventoryByIdAsync(int inventoryId)
        {
            return await _context.Inventories.Include(i => i.Product).FirstOrDefaultAsync(i => i.InventoryId == inventoryId);
        }

        public async Task AddInventoryAsync(Inventory inventory)
        {
            await _context.Inventories.AddAsync(inventory);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateInventoryAsync(Inventory inventory)
        {
            _context.Inventories.Update(inventory);
            await _context.SaveChangesAsync();
        }

        public async Task DeleteInventoryAsync(int inventoryId)
        {
            var inventory = await _context.Inventories.FindAsync(inventoryId);
            if (inventory != null)
            {
                _context.Inventories.Remove(inventory);
                await _context.SaveChangesAsync();
            }
        }
    }
}
